package cc.uncarbon.module.custom.service;

import cc.uncarbon.framework.core.constant.HelioConstant;
import cc.uncarbon.framework.core.exception.BusinessException;
import cc.uncarbon.framework.core.page.PageParam;
import cc.uncarbon.framework.core.page.PageResult;
import cc.uncarbon.module.custom.entity.OrdersEntity;
import cc.uncarbon.module.custom.mapper.OrdersMapper;
import cc.uncarbon.module.custom.model.request.AdminOrdersInsertOrUpdateDTO;
import cc.uncarbon.module.custom.model.request.AdminOrdersListDTO;
import cc.uncarbon.module.custom.model.response.OrdersBO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;


/**
 * 订单
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class OrdersService {

    private final OrdersMapper ordersMapper;


    /**
     * 后台管理-分页列表
     */
    public PageResult<OrdersBO> adminList(PageParam pageParam, AdminOrdersListDTO dto) {
        Page<OrdersEntity> entityPage = ordersMapper.selectPage(
                new Page<>(pageParam.getPageNum(), pageParam.getPageSize()),
                new QueryWrapper<OrdersEntity>()
                        .lambda()
                        // 订单编号
                        .like(CharSequenceUtil.isNotBlank(dto.getOrderNo()), OrdersEntity::getOrderNo, CharSequenceUtil.cleanBlank(dto.getOrderNo()))
                        // 用户id
                        .eq(ObjectUtil.isNotNull(dto.getUserId()), OrdersEntity::getUserId, dto.getUserId())
                        // 实际需要支付的价格，单位分，优惠前
                        .eq(ObjectUtil.isNotNull(dto.getPrice()), OrdersEntity::getPrice, dto.getPrice())
                        // 实际支付金额
                        .eq(ObjectUtil.isNotNull(dto.getPayMoney()), OrdersEntity::getPayMoney, dto.getPayMoney())
                        // 用户代金券id
                        .eq(ObjectUtil.isNotNull(dto.getUserCouponId()), OrdersEntity::getUserCouponId, dto.getUserCouponId())
                        // 用户等级
                        .eq(ObjectUtil.isNotNull(dto.getVipLevel()), OrdersEntity::getVipLevel, dto.getVipLevel())
                        // 美容师id
                        .eq(ObjectUtil.isNotNull(dto.getStaffId()), OrdersEntity::getStaffId, dto.getStaffId())
                        // 备注
                        .like(CharSequenceUtil.isNotBlank(dto.getRemark()), OrdersEntity::getRemark, CharSequenceUtil.cleanBlank(dto.getRemark()))
                        // 状态（0禁用，1正常
                        .eq(ObjectUtil.isNotNull(dto.getStatus()), OrdersEntity::getStatus, dto.getStatus())
                        // 店铺id
                        .eq(ObjectUtil.isNotNull(dto.getStoreId()), OrdersEntity::getStoreId, dto.getStoreId())
                        // 时间区间
                        .between(ObjectUtil.isNotNull(dto.getBeginAt()) && ObjectUtil.isNotNull(dto.getEndAt()), OrdersEntity::getCreatedAt, dto.getBeginAt(), dto.getEndAt())
                        // 排序
                        .orderByDesc(OrdersEntity::getCreatedAt)
        );

        return this.entityPage2BOPage(entityPage);
    }

    /**
     * 根据 ID 取详情
     *
     * @param id 主键ID
     * @return null or BO
     */
    public OrdersBO getOneById(Long id) {
        return this.getOneById(id, false);
    }

    /**
     * 根据 ID 取详情
     *
     * @param id 主键ID
     * @param throwIfInvalidId 是否在 ID 无效时抛出异常
     * @return null or BO
     */
    public OrdersBO getOneById(Long id, boolean throwIfInvalidId) throws BusinessException {
        OrdersEntity entity = ordersMapper.selectById(id);
        if (throwIfInvalidId && entity == null) {
            throw new BusinessException(400, "无效订单ID");
        }

        return this.entity2BO(entity);
    }

    /**
     * 后台管理-新增
     */
    @Transactional(rollbackFor = Exception.class)
    public Long adminInsert(AdminOrdersInsertOrUpdateDTO dto) {
        log.info("[后台管理-订单-新增] >> DTO={}", dto);
        this.checkExistence(dto);

        dto.setId(null);
        OrdersEntity entity = new OrdersEntity();
        BeanUtil.copyProperties(dto, entity);

        ordersMapper.insert(entity);

        return entity.getId();
    }

    /**
     * 后台管理-编辑
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminUpdate(AdminOrdersInsertOrUpdateDTO dto) {
        log.info("[后台管理-订单-编辑] >> DTO={}", dto);
        this.checkExistence(dto);

        OrdersEntity entity = new OrdersEntity();
        BeanUtil.copyProperties(dto, entity);

        ordersMapper.updateById(entity);
    }

    /**
     * 后台管理-删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminDelete(Collection<Long> ids) {
        log.info("[后台管理-订单-删除] >> ids={}", ids);
        ordersMapper.deleteBatchIds(ids);
    }


    /*
    ----------------------------------------------------------------
                        私有方法 private methods
    ----------------------------------------------------------------
     */

    /**
     * 实体转 BO
     *
     * @param entity 实体
     * @return BO
     */
    private OrdersBO entity2BO(OrdersEntity entity) {
        if (entity == null) {
            return null;
        }

        OrdersBO bo = new OrdersBO();
        BeanUtil.copyProperties(entity, bo);

        // 可以在此处为BO填充字段

        return bo;
    }

    /**
     * 实体 List 转 BO List
     *
     * @param entityList 实体 List
     * @return BO List
     */
    private List<OrdersBO> entityList2BOs(List<OrdersEntity> entityList) {
        if (CollUtil.isEmpty(entityList)) {
            return Collections.emptyList();
        }

        // 深拷贝
        List<OrdersBO> ret = new ArrayList<>(entityList.size());
        entityList.forEach(
            entity -> ret.add(this.entity2BO(entity))
        );

        return ret;
    }

    /**
     * 实体分页转 BO 分页
     *
     * @param entityPage 实体分页
     * @return BO 分页
     */
    private PageResult<OrdersBO> entityPage2BOPage(Page<OrdersEntity> entityPage) {
        return new PageResult<OrdersBO>()
            .setCurrent(entityPage.getCurrent())
            .setSize(entityPage.getSize())
            .setTotal(entityPage.getTotal())
            .setRecords(this.entityList2BOs(entityPage.getRecords()));
    }

    /**
     * 检查是否已存在同名数据
     *
     * @param dto DTO
     */
    private void checkExistence(AdminOrdersInsertOrUpdateDTO dto) {
        /*
        可以根据自己业务需要，解禁这段代码，修改判断条件和文案

        OrdersEntity existingEntity = ordersMapper.selectOne(
                new QueryWrapper<OrdersEntity>()
                        .lambda()
                        .select(OrdersEntity::getId)
                        .eq(OrdersEntity::getTitle, dto.getTitle())
                        .last(HelioConstant.CRUD.SQL_LIMIT_1)
        );

        if (existingEntity != null && !existingEntity.getId().equals(dto.getId())) {
            throw new BusinessException(400, "已存在相同订单，请重新输入");
        }
        */
    }

}
